using AutoMapper;
using B.S.RbacData.ErrorCode;
using B.S.RbacData.Infrastructure;
using ContentmanagementBase.Domain;
using ContentmanagementBaseWrite.API.Applications.Commands.Popularizations;
using MediatR;

namespace ContentmanagementBaseWrite.API.Applications.Commandhandlters.Popularizations
{
    /// <summary>
    /// 更新疾病科普命令处理器
    /// </summary>
    public class UpdatePopularizationCommandHandler : IRequestHandler<UpdatePopularizationCommand, ApiResult<int>>
    {
        /// <summary>
        /// 疾病科普仓储
        /// </summary>
        private readonly IBaseRepository<PopularScienceDiseaseModel> _popularizationRepository;
        /// <summary>
        /// 映射器
        /// </summary>
        private readonly IMapper _mapper;
        /// <summary>
        /// 日志记录器
        /// </summary>
        private readonly ILogger<UpdatePopularizationCommandHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="popularizationRepository">疾病科普仓储</param>
        /// <param name="mapper">映射器</param>
        /// <param name="logger">日志记录器</param>
        public UpdatePopularizationCommandHandler(IBaseRepository<PopularScienceDiseaseModel> popularizationRepository, IMapper mapper, ILogger<UpdatePopularizationCommandHandler> logger)
        {
            _popularizationRepository = popularizationRepository;
            _mapper = mapper;
            _logger = logger;
        }

        /// <summary>
        /// 处理更新疾病科普命令
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns></returns>
        public async Task<ApiResult<int>> Handle(UpdatePopularizationCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始处理疾病科普更新命令，ID：{Id}，标题：{Title}", request.Id, request.PopularScienceTitle);

                // 验证疾病科普是否存在
                var existingPopularization = _popularizationRepository.GetAll().FirstOrDefault(x => x.Id == request.Id && !x.IsDeleted);
                if (existingPopularization == null)
                {
                    _logger.LogWarning("疾病科普不存在，ID：{Id}", request.Id);
                    return new ApiResult<int>
                    {
                        code = ResultEnumCode.error,
                        message = "疾病科普不存在！",
                        data = 0
                    };
                }

                // 验证疾病科普标题是否与其他科普重复（排除自身）
                var existingPopularizations = _popularizationRepository.GetAll()
                    .Where(x => x.PopularScienceTitle == request.PopularScienceTitle && x.Id != request.Id && !x.IsDeleted);

                if (existingPopularizations.Any())
                {
                    _logger.LogWarning("疾病科普标题已存在，标题：{Title}", request.PopularScienceTitle);
                    return new ApiResult<int>
                    {
                        code = ResultEnumCode.error,
                        message = "疾病科普标题已存在！",
                        data = 0
                    };
                }

                _logger.LogDebug("疾病科普验证通过，开始更新疾病科普信息");

                // 更新疾病科普信息
                existingPopularization.PopularScienceTitle = request.PopularScienceTitle;
                existingPopularization.PopularScienceImages = request.PopularScienceImages;
                existingPopularization.DiseaseType = request.DiseaseType;
                existingPopularization.PopularScienceStatus = request.PopularScienceStatus;
                existingPopularization.IsRecommended = request.IsRecommended;
                existingPopularization.DetailedContent = request.DetailedContent;
                existingPopularization.UpdatedTime = DateTime.Now;
                existingPopularization.UpdatedBy = 1; // 这里应该从当前用户上下文获取

                _logger.LogDebug("疾病科普信息更新完成，准备保存到数据库");

                // 保存到数据库
                var result = await _popularizationRepository.UpdateAsync(existingPopularization);
                _logger.LogInformation("数据库更新完成，影响行数：{Result}", result);

                if (result > 0)
                {
                    _logger.LogInformation("疾病科普更新成功，ID：{Id}", request.Id);
                    return new ApiResult<int>
                    {
                        code = ResultEnumCode.Ok,
                        message = "疾病科普更新成功",
                        data = request.Id
                    };
                }
                else
                {
                    _logger.LogWarning("疾病科普更新失败，数据库未返回影响行数");
                    return new ApiResult<int>
                    {
                        code = ResultEnumCode.fails,
                        message = "疾病科普更新失败",
                        data = 0
                    };
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "疾病科普更新过程中发生异常，ID：{Id}", request.Id);
                return new ApiResult<int>
                {
                    code = ResultEnumCode.fails,
                    message = $"疾病科普更新异常：{ex.Message}",
                    data = 0
                };
            }
        }
    }
}